package com.yserp.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sf.csim.express.service.CallExpressServiceTools;
import com.sf.dto.CargoInfoDto;
import com.sf.dto.WaybillDto;
import com.sf.util.Base64ImageTools;
import com.sf.util.MyJsonUtil;
import com.yserp.kd.entity.TKdUserConfEntity;
import com.yserp.kd.entity.TWlApiEntity;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jeecgframework.core.common.dao.jdbc.JdbcDao;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.web.system.sms.service.TSSmsTemplateSqlServiceI;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * 
  * @ClassName: TuiSongMsgUtil 统一发送消息的公用方法
  * @Description: TODO
  * @author Comsys-skyCc cmzcheng@gmail.com
  * @date 2014-9-18 下午3:20:34
  *
 */
public class kdUtil {

public static SfExpressResponse  doChaxun(TWlApiEntity tWlApi,TKdUserConfEntity tKdUserConf){
        String URL = tKdUserConf.getXiadanurl();
        String clientCode = tKdUserConf.getAppid();
        String checkword = tKdUserConf.getAppsec();
        Map<String,String> query = new HashMap<String, String>();
        query.put("orderNo",tWlApi.getMailno());
        String orderxml = getRouteServiceRequestXml(clientCode,query);
        String result="";
        CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
        String resulttemp = CallExpressServiceTools.callSfExpressServiceByCSIM(URL, orderxml, clientCode, checkword);
            SfExpressResponse response = (SfExpressResponse)
                    XMLUtil.convertXmlStrToObject(SfExpressResponse.class, resulttemp);
            return response;
}
    /**
     * 获取顺丰路由查询接口xml
     * @param params
     * @return
     */
    private static String getRouteServiceRequestXml(String clientCode,Map<String,String> params){
        String orderNo = params.get("orderNo");
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("<Request service='RouteService' lang='zh-CN'>");
        strBuilder.append("<Head>" + clientCode + "</Head>");
        strBuilder.append("<Body>");
        strBuilder.append("<RouteRequest").append(" ");
        strBuilder.append("tracking_type='2'").append(" ");
        strBuilder.append("tracking_number='" + orderNo.toString().trim() + "" + "'").append(" >");
        strBuilder.append("</RouteRequest>");
        strBuilder.append("</Body>");
        strBuilder.append("</Request>");
        return strBuilder.toString();
    }
    public static Map<String,String> doXiadan(TWlApiEntity tWlApi,TKdUserConfEntity tKdUserConf){
        String result="";
        Map<String,String> resultmap = new HashMap<String, String>();
//            String URL = "http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService";
//            String clientCode = "SMJWRJ";
//            String checkword = "fkyYr5u1JND5wbogQz6owTo9LTqUgzjD";
                    String URL = tKdUserConf.getXiadanurl();
            String clientCode = tKdUserConf.getAppid();
            String checkword = tKdUserConf.getAppsec();
            String orderxml = "<Request service = 'OrderService' lang = 'zh-CN'> " +
                "<Head>"+clientCode+"</Head>  " +
                "<Body> " +
                "<Order " +
                "orderid = '"+tWlApi.getOrderid()+"' " +
                "express_type = '1' "  +
                "j_province = '"+tWlApi.getJprovince()+"' " +
                " j_city = '"+tWlApi.getJcity()+"' " +
                "j_company = '"+tWlApi.getJcompany()+"' " +
                "j_contact = '"+tWlApi.getJcontact()+"' " +
                "j_tel = '"+tWlApi.getJtel()+"' " +
                "j_address = '"+tWlApi.getJaddress()+"' " +
                "d_province = '"+tWlApi.getDprovince()+"' " +
                "d_city = '"+tWlApi.getDcity()+"' " +
                "d_county = '"+tWlApi.getDcounty()+"' " +
                "d_company = '"+tWlApi.getDcompany()+"' " +
                "d_contact = '"+tWlApi.getDcontact()+"' " +
                "d_tel = '"+tWlApi.getDtel()+"' " +
                "d_address = '"+tWlApi.getDaddress()+"' " +
                "parcel_quantity = '"+tWlApi.getParcelQuantity()+"' " +
                "pay_method='3' " +
                "custid = '"+tWlApi.getCustid()+"' " +
                "customs_batchs='' " +
                "cargo= '"+tWlApi.getName()+"' " +
                    "count= '"+tWlApi.getCount()+"' " +
                    "unit= '"+tWlApi.getUnit()+"' >" +
//                "<AddedService name='COD' value='1.01' value1='7550010173'/> " +
                "</Order> " +
                "</Body>  " +
                "</Request> ";

        CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
        String resulttemp = CallExpressServiceTools.callSfExpressServiceByCSIM(URL, orderxml, clientCode, checkword);
        if (resulttemp != null) {

            SfExpressResponse response = (SfExpressResponse)
                    XMLUtil.convertXmlStrToObject(SfExpressResponse.class,resulttemp);
            if(response.getHead().equals("OK"))
            {
                String destcode =  response.getBody().getOrderResponse().getDestCode();
                String origincode = response.getBody().getOrderResponse().getOriginCode();
                String mailno = response.getBody().getOrderResponse().getMailNo();
                resultmap.put("head",response.getHead());
                resultmap.put("destcode",destcode);
                resultmap.put("origincode",origincode);
                resultmap.put("mailno",mailno);

            }else{
                if(response.getHead().equals("ERR")&&response.getERROR().getCode().equals(tKdUserConf.getAppby1())){
                    String orderxmlre = "<Request service='OrderSearchService' lang='zh-CN'>" +
                            "<Head>\"+clientCode+\"</Head> " +
                            "<Body> " +
                            "<OrderSearch orderid= '"+tWlApi.getOrderid()+"' "+
                            "</Body> " +
                            "</Request> ";
                    resulttemp = CallExpressServiceTools.callSfExpressServiceByCSIM(URL, orderxmlre, clientCode, checkword);
                     response = (SfExpressResponse)
                            XMLUtil.convertXmlStrToObject(SfExpressResponse.class,resulttemp);
                    if(response.getHead().equals("OK"))
                    {
                        String destcode =  response.getBody().getOrderResponse().getDestCode();
                        String origincode = response.getBody().getOrderResponse().getOriginCode();
                        String mailno = response.getBody().getOrderResponse().getMailNo();
                        resultmap.put("head",response.getHead());
                        resultmap.put("destcode",destcode);
                        resultmap.put("origincode",origincode);
                        resultmap.put("mailno",mailno);

                    }else{
                        resultmap.put("head",response.getHead());
                        resultmap.put("errcode",response.getERROR().getCode());
                        resultmap.put("errtext",response.getERROR().getText());
                    }
                }else{
                    resultmap.put("head",response.getHead());
                    resultmap.put("errcode",response.getERROR().getCode());
                    resultmap.put("errtext",response.getERROR().getText());
                }
            }
//                String destcode = itemEle.elementTextTrim("destcode"); // 拿到head下的子节点script下的字节点username的值
//                String origincode = itemEle.elementTextTrim("origincode");
//                String mailno = itemEle.elementTextTrim("mailno");
//                System.out.println("destcode:" + destcode);
//                System.out.println("origincode:" + origincode);
//                System.out.println("mailno:" + mailno);

            System.out.println("--------------------------------------");
            System.out.println("Response content: " + resulttemp);
            System.out.println("--------------------------------------");
        }
//        result = resulttemp;
        return  resultmap;
    }
    public static String doPrint(TWlApiEntity tWlApi,TKdUserConfEntity tKdUserConf) throws Exception {
        String result=null;
        String url = tKdUserConf.getPrinturl();

        //根据业务需求确定请求地址
        String reqURL = url;

        //电子面单顶部是否需要logo
        boolean topLogo = true;//true 需要logo  false 不需要logo
        if (reqURL.contains("V2.0") && topLogo) {
            reqURL = reqURL.replace("V2.0", "V2.1");
        }

        if (reqURL.contains("V3.0") && topLogo) {
            reqURL = reqURL.replace("V3.0", "V3.1");
        }

        System.out.println(reqURL);

        /**注意 需要使用对应业务场景的url  **/
        URL myURL = new URL(reqURL);

        //其中127.0.0.1:4040为打印服务部署的地址（端口如未指定，默认为4040），
        //type为模板类型（支持两联、三联，尺寸为100mm*150mm和100mm*210mm，type为poster_100mm150mm和poster_100mm210mm）
        //A5 poster_100mm150mm   A5 poster_100mm210mm
        //output为输出类型,值为print或image，如不传，
        //默认为print（print 表示直接打印，image表示获取图片的BASE64编码字符串）
        //V2.0/V3.0模板顶部是带logo的  V2.1/V3.1顶部不带logo

        HttpURLConnection httpConn = (HttpURLConnection) myURL.openConnection();
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setUseCaches(false);
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        httpConn.setConnectTimeout(5000);
        httpConn.setReadTimeout(2 * 5000);

        List<WaybillDto> waybillDtoList = new ArrayList<>();
        WaybillDto dto = new WaybillDto();


        //这个必填
        dto.setAppId(tKdUserConf.getAppid());//对应clientCode
        dto.setAppKey(tKdUserConf.getAppsec());//对应checkWord


        dto.setMailNo(tWlApi.getMailno());
        //dto.setMailNo("755123456788,001000000002");//子母单方式


        //收件人信息
        dto.setConsignerProvince(tWlApi.getDprovince());
        dto.setConsignerCity(tWlApi.getDcity());
        dto.setConsignerCounty(tWlApi.getDcounty());
        dto.setConsignerAddress(tWlApi.getDaddress()); //详细地址建议最多30个字  字段过长影响打印效果
        dto.setConsignerCompany(tWlApi.getDcompany());
        dto.setConsignerMobile(tWlApi.getDmobile());
        dto.setConsignerName(tWlApi.getDcontact());
        dto.setConsignerShipperCode(tWlApi.getDpostCode());
        dto.setConsignerTel(tWlApi.getDtel());


        //寄件人信息
        dto.setDeliverProvince(tWlApi.getJprovince());
        dto.setDeliverCity(tWlApi.getJcity());
        dto.setDeliverCounty(tWlApi.getJcounty());
        dto.setDeliverCompany(tWlApi.getJcompany());
        dto.setDeliverAddress(tWlApi.getJaddress());//详细地址建议最多30个字  字段过长影响打印效果
        dto.setDeliverName(tWlApi.getJcontact());
        dto.setDeliverMobile(tWlApi.getJmobile());
        dto.setDeliverShipperCode(tWlApi.getJpostCode());
        dto.setDeliverTel(tWlApi.getJtel());


        dto.setDestCode(tWlApi.getDestcode());//目的地代码 参考顺丰地区编号
        dto.setZipCode(tWlApi.getOrigincode());//原寄地代码 参考顺丰地区编号

        //签回单号  签单返回服务 会打印两份快单 其中第二份作为返寄的单
        //如客户使用签单返还业务则需打印“POD”字段，用以提醒收派员此件为签单返还快件。
        // dto.setReturnTrackingNo("755123457778");

        //陆运E标示
        //业务类型为“电商特惠、顺丰特惠、电商专配、陆运件”则必须打印E标识，用以提示中转场分拣为陆运
        dto.setElectric("E");


        //快递类型
        //1 ：标准快递   2.顺丰特惠   3： 电商特惠   5：顺丰次晨  6：顺丰即日  7.电商速配   15：生鲜速配
        dto.setExpressType(Integer.parseInt(tWlApi.getExpressType().trim()));

        //COD代收货款金额,只需填金额, 单位元- 此项和月结卡号绑定的增值服务相关
//        dto.setCodValue("999.9");

//        dto.setInsureValue("501");//声明货物价值的保价金额,只需填金额,单位元
        dto.setMonthAccount(tWlApi.getCustid());//月结卡号
        dto.setPayMethod(1);// 1-寄付 2-到付 3-第三方支付


        /**丰密运单相关-如非使用丰密运单模板 不需要设置以下值**/
//		dto.setDestRouteLabel("755WE-571A3");
//		dto.setPrintIcon("1111");
//		dto.setProCode("T6");
//		dto.setAbFlag("A");
//		dto.setXbFlag("XB");
//		dto.setCodingMapping("F33");
//		dto.setCodingMappingOut("1A");
//		dto.setDestTeamCode("012345678");
//		dto.setSourceTransferCode("021WTF");
        //对应下订单设置路由标签返回字段twoDimensionCode 该参数是丰密面单的二维码图
//		dto.setQRCode("MMM={'k1':'755WE','k2':'755BF','k3':'','k4':'T6','k5':'755123456789','k6':'A'}");


        //加密项
        dto.setEncryptCustName(true);//加密寄件人及收件人名称
        dto.setEncryptMobile(true);//加密寄件人及收件人联系手机


        CargoInfoDto cargo = new CargoInfoDto();
        cargo.setCargo(tWlApi.getName());
        cargo.setCargoCount(tWlApi.getCount());
        cargo.setCargoUnit(tWlApi.getUnit());
        cargo.setSku(tWlApi.getBrand());
        cargo.setRemark(tWlApi.getRemark());

//        CargoInfoDto cargo2 = new CargoInfoDto();
//        cargo2.setCargo("苹果macbook pro");
//        cargo2.setCargoCount(1);
//        cargo2.setCargoUnit("件");
//        cargo2.setSku("00015646");
//        cargo2.setRemark("笔记本贵重物品 小心轻放");

        List<CargoInfoDto> cargoInfoList = new ArrayList<>();
//        cargoInfoList.add(cargo2);
        cargoInfoList.add(cargo);

        dto.setCargoInfoDtoList(cargoInfoList);
        waybillDtoList.add(dto);


        System.out.println("请求参数： " + MyJsonUtil.object2json(dto));


        ObjectMapper objectMapper = new ObjectMapper();
        StringWriter stringWriter = new StringWriter();
        objectMapper.writeValue(stringWriter, waybillDtoList);

        httpConn.getOutputStream().write(stringWriter.toString().getBytes());
        httpConn.getOutputStream().flush();
        httpConn.getOutputStream().close();
        InputStream in = httpConn.getInputStream();

        BufferedReader in2 = new BufferedReader(new InputStreamReader(in));

        String y = "";


        String strImg = "";
        while ((y = in2.readLine()) != null) {

            strImg = y.substring(y.indexOf("[") + 1, y.length() - "]".length() - 1);
            if (strImg.startsWith("\"")) {
                strImg = strImg.substring(1, strImg.length());
            }
            if (strImg.endsWith("\"")) {
                strImg = strImg.substring(0, strImg.length() - 1);
            }

        }

        //将换行全部替换成空
        strImg = strImg.replace("\\n", "");
        //System.out.println(strImg);

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String dateStr = format.format(new Date());

        if (strImg.contains("\",\"")) {
            //如子母单及签回单需要打印两份或者以上
            String[] arr = strImg.split("\",\"");

            /**输出图片到本地 支持.jpg、.png格式**/
            for (int i = 0; i < arr.length; i++) {
                Base64ImageTools.generateImage(arr[i].toString(), "D:\\qiaoWay" + dateStr + "-" + i + ".jpg");

            }
        } else {
            Base64ImageTools.generateImage(strImg, "D:\\qiaoWaybill" + dateStr + ".jpg");

        }

        result = "已打印";
        return  result;
    }

    public  static  String getdocnum(String objtype){
        JdbcDao jdbcDao = ApplicationContextUtil.getContext().getBean(JdbcDao.class);
        Statement stmt = null;
        ResultSet rs = null;
        Connection conn = null;
        String docnum=null;
        try {
            conn = jdbcDao.getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        CallableStatement proc = null;
        Date d=new Date();//获取时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//转换格式

        try{
        proc = conn.prepareCall("{ call p_createdocnum(?,?,?) }");
        proc.setString(1, objtype);
        proc.setString(2, sdf.format(d));
        proc.registerOutParameter(3, Types.VARCHAR);
        proc.execute();
        docnum = proc.getString(3);
        }catch (Exception e){

        }
        return  docnum;
    }

	public static Map<String,String> saveentity(String objtype,String transtype,String doc){
		JdbcDao jdbcDao = ApplicationContextUtil.getContext().getBean(JdbcDao.class);
		Statement stmt = null;
		ResultSet rs = null;
		Connection conn = null;
        Map<String,String> resultmap = new HashMap<String, String>() ;
        try {
            conn = jdbcDao.getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        CallableStatement proc = null;

        try{
            proc = conn.prepareCall("{ call p_savestock(?,?,?,?,?) }");
            proc.setString(1, objtype);
            proc.setString(2, transtype );
            proc.setString(3, doc );
            proc.registerOutParameter(4, Types.VARCHAR);
            proc.registerOutParameter(5, Types.VARCHAR);
            proc.execute();
            resultmap.put("code",proc.getString(4));
            resultmap.put("message",proc.getString(5));
        }catch (Exception e){

        }
        return  resultmap;
	}
	public static TSSmsTemplateSqlServiceI getTssmsTemplateSqlInstance(){
		
		TSSmsTemplateSqlServiceI tSSmsTemplateSqlService = ApplicationContextUtil.getContext().getBean(TSSmsTemplateSqlServiceI.class);
			
		return tSSmsTemplateSqlService;
	}


}
